package com.ittaotao.module.anno.utils;

import com.ittaotao.module.anno.anno.Autowired;
import com.ittaotao.module.anno.anno.Service;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import org.junit.Test;
import org.reflections.Reflections;


import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author tao.liu
 * @desc bean工厂
 */
public class BeanFactory {
    private static Map<String, Object> map = new HashMap<>();


    static Object getBean(String name, Reflections reflections) {
        try {

            Class<?> clazz = Class.forName(name);

            if (clazz.isInterface()) {
                Set<Class<? extends Object>> myClasses = reflections.getSubTypesOf((Class<Object>) clazz);
                for (Class<? extends Object> impl : myClasses) {
                    map.put(clazz.getSimpleName(), impl);
                }
            }

            //获取所有类上面的@Service 注解
            if (clazz.isAnnotationPresent(Service.class)) {
                //获取该service下的Autowired 注解
                Field[] methodAnnotations = clazz.getDeclaredFields();
                for (Field field : methodAnnotations) {
                    if (field.isAnnotationPresent(Autowired.class)) {
                        field.setAccessible(true);

                        if (field.getType().isInterface()) {
                            String[] fieldNames = field.getType().getName().split("\\.");
                            String fieldName = field.getName();
                            ClassPool pool = ClassPool.getDefault();
                            CtClass ctClass = pool.makeClass(field.getType().getName());
                            ctClass.addMethod(CtMethod.make(fieldName, ctClass));

                            System.out.println("接口类型的Autowired" + field.getType());
                        }

                    }
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Test
    public void test() {
        Set<String> packages = getClassName("com.ittaotao", true);
        Reflections reflections = new Reflections("com.ittaotao");
        packages.forEach(item -> {
            getBean(item, reflections);
        });

    }

    /**
     * 获取某包下所有类
     *
     * @param packageName 包名
     * @param isRecursion 是否遍历子包
     * @return 类的完整名称
     */
    public static Set<String> getClassName(String packageName, boolean isRecursion) {
        Set<String> classNames = null;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String packagePath = packageName.replace(".", "/");

        URL url = loader.getResource(packagePath);
        if (url != null) {
            String protocol = url.getProtocol();
            if (protocol.equals("file")) {
                classNames = getClassNameFromDir(url.getPath(), packageName, isRecursion);
            } else if (protocol.equals("jar")) {
                JarFile jarFile = null;
                try {
                    jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (jarFile != null) {
                    getClassNameFromJar(jarFile.entries(), packageName, isRecursion);
                }
            }
        } else {
            /*从所有的jar包中查找包名*/
            classNames = getClassNameFromJars(((URLClassLoader) loader).getURLs(), packageName, isRecursion);
        }

        return classNames;
    }

    /**
     * 从项目文件获取某包下�?有类
     *
     * @param filePath    文件路径
     * @param isRecursion 是否遍历子包
     * @return 类的完整名称
     */
    private static Set<String> getClassNameFromDir(String filePath, String packageName, boolean isRecursion) {
        Set<String> className = new HashSet<>();
        File file = new File(filePath);
        File[] files = file.listFiles();
        for (File childFile : files) {

            if (childFile.isDirectory()) {
                if (isRecursion) {
                    className.addAll(getClassNameFromDir(childFile.getPath(), packageName + "." + childFile.getName(), isRecursion));
                }
            } else {
                String fileName = childFile.getName();
                //endsWith() 方法用于测试字符串是否以指定的后�?结束�?  !fileName.contains("$") 文件名中不包? '$'
                if (fileName.endsWith(".class") && !fileName.contains("$")) {
                    className.add(packageName + "." + fileName.replace(".class", ""));
                }
            }
        }

        return className;
    }


    /**
     * @param jarEntries
     * @param packageName
     * @param isRecursion
     * @return
     */
    private static Set<String> getClassNameFromJar(Enumeration<JarEntry> jarEntries, String packageName, boolean isRecursion) {
        Set<String> classNames = new HashSet();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (!jarEntry.isDirectory()) {
                /*
                 * 这里是为了方便，先把"/" 转成 "." 再判�? ".class" 的做法可能会有bug
                 * (FIXME: 先把"/" 转成 "." 再判�? ".class" 的做法可能会有bug)
                 */
                String entryName = jarEntry.getName().replace("/", ".");
                if (entryName.endsWith(".class") && !entryName.contains("$") && entryName.startsWith(packageName)) {
                    entryName = entryName.replace(".class", "");
                    if (isRecursion) {
                        classNames.add(entryName);
                    } else if (!entryName.replace(packageName + ".", "").contains(".")) {
                        classNames.add(entryName);
                    }
                }
            }
        }

        return classNames;
    }

    /**
     * 从所有jar中搜索该包，并获取该包下�?有类
     *
     * @param urls        URL集合
     * @param packageName
     * @param isRecursion 是否遍历子包
     * @return 类的完整名称
     */
    private static Set<String> getClassNameFromJars(URL[] urls, String packageName, boolean isRecursion) {
        Set<String> classNames = new HashSet<>();

        for (int i = 0; i < urls.length; i++) {
            String classPath = urls[i].getPath();
            //不必搜索classes文件�?
            if (classPath.endsWith("classes/")) {
                continue;
            }

            JarFile jarFile = null;
            try {
                jarFile = new JarFile(classPath.substring(classPath.indexOf("/")));
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (jarFile != null) {
                classNames.addAll(getClassNameFromJar(jarFile.entries(), packageName, isRecursion));
            }
        }

        return classNames;
    }


}
